﻿IF EXISTS (
    SELECT
      1
    FROM sysobjects
    WHERE id = OBJECT_ID('bd_proc_repair_after_approve')
      AND type IN ('P', 'PC')
  )
  DROP PROCEDURE bd_proc_repair_after_approve

GO


-- =============================================
-- Author:      YFC
-- Create date: 2020-07-17 11:02:27
-- Database:    [scm_main-hysj2]
-- Description: 补出勤管理-补出勤审批结束后操作
-- =============================================

CREATE PROCEDURE bd_proc_repair_after_approve
  @orderId  INT,
  @approveStatus  INT
AS
BEGIN
  SET NOCOUNT ON;

  BEGIN TRY
  	BEGIN TRANSACTION
  		
      --审批最终通过后，生成打卡记录
      IF ISNULL(@approveStatus, 0) = 3 
      BEGIN  
        DECLARE @operatorId BIGINT, @begin DATE, @end DATE
        SELECT @operatorId = creater_id, @begin = start_date, @end = end_date FROM bd_repair_attendance WHERE order_id = @orderId
      
        INSERT INTO kt_jl (sj, user_serial, fx, lx, yich, gly_no, jl_type, whether_validity, mode, order_id, pc_ip, pc_name, create_time, valid_date)
        SELECT sj, user_serial, 0, 0, 0, CAST(@operatorId AS VARCHAR), 0, 0, 1, order_id, pc_ip, pc_name, GETDATE(), NULL
        FROM lr_jl WHERE order_id = @orderId
  
        --重新计算考勤      
  			DECLARE @users VARCHAR(MAX) = ''
  			
  			SELECT DISTINCT
  				@users = @users + CAST(u.user_serial AS VARCHAR(100)) + ','
  			FROM lr_jl u
  			WHERE u.order_id = @orderId
  
  			SET @users = SUBSTRING(@users,0, LEN(@users))
  			EXEC bd_proc_timecard_extend @begin, @end, @users, 1
      END
  	COMMIT TRANSACTION
  END TRY
  BEGIN CATCH
    DECLARE @errStr VARCHAR(MAX) = ERROR_MESSAGE();

    IF XACT_STATE() <> 0
    BEGIN
      ROLLBACK TRANSACTION;
      RAISERROR (@errStr, 16, 1);
    END;
  END CATCH;

  SET NOCOUNT OFF;
END